import { ScrollView, View } from "@tarojs/components"
import React, { useCallback, useEffect, useRef, useState } from "react"
import { AtLoadMore } from "taro-ui"
import Taro, { useDidShow } from "@tarojs/taro"
import "./index.scss"
import AdminOrderItem from "./components/adminOrderItem"
import http from "../../utils/http"
import { debounce } from "../../utils"
import Modal from "../../components/Modal"

const statusTab = [
  // {
  //   label: "待确认",
  //   value: 0,
  // },
  {
    label: "待支付",
    value: 1,
  },
  {
    label: "待穿线",
    value: 2,
  },
  {
    label: "待取拍",
    value: 3,
  },
  // {
  //   label: "已完成",
  //   value: 4,
  // },
  // {
  //   label: "已取消",
  //   value: 5,
  // },
]
export default function () {
  const [tabCurrent, setTabCurrent] = useState(0)
  const [statusTabCurrent, setStatusTabCurrent] = useState(1)
  const [orderList, setOrderList] = useState([])
  const [status, setStatus] = useState("more")
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const [showModal, setShowModal] = useState(false)
  const [modalItem, setModalItem] = useState(null)
  const pageDataRef = useRef({
    pageSize: 20,
    pageNum: 0,
  })
  const isFirstLoadRef = useRef(true)

  const getOrderList = useCallback(
    debounce(async page => {
      if (status === "loading") return
      if (page.pageNum == 1) {
        setOrderList([])
      }
      setStatus("loading")
      const { data } = await http.post("/core/ticket/search/page/list", {
        ...page,
      })
      if (data) {
        let newList = [...orderList]
        if (page.pageNum === 1) {
          newList = data.records || []
        } else {
          console.log("newList.length", newList.length)
          data.records.forEach(item => {
            newList.push(item)
          })
        }
        setOrderList(newList)
        pageDataRef.current = {
          pageNum: data.current,
          pageSize: data.size,
        }
        setRefresherTriggeredStatus(false)
        if (data.total > newList.length) {
          setStatus("more")
        } else {
          setStatus("noMore")
        }
      } else {
        setStatus("noMore")
      }
    }, 200),
    [orderList]
  )

  const onScrollLoad = () => {
    if (status === "loading" || status === "noMore") return
    getOrderList({
      pageSize: pageDataRef.current.pageSize,
      pageNum: pageDataRef.current.pageNum + 1,
      ...getParams(),
    })
  }

  const getParams = () => {
    const params = {}
    if (tabCurrent == 0) {
      params.status = [0]
    } else if (tabCurrent == 1) {
      params.status = [statusTabCurrent]
    } else if (tabCurrent == 2) {
      params.status = [4, 5]
    }
    return params
  }

  useEffect(() => {
    const params = {
      pageSize: pageDataRef.current.pageSize,
      pageNum: 1,
    }
    getOrderList({
      ...params,
      ...getParams(),
    })
  }, [statusTabCurrent, tabCurrent])

  useDidShow(() => {
    if (isFirstLoadRef.current) {
      isFirstLoadRef.current = false
      const params = Taro.getCurrentInstance().router.params
      params.tabCurrent && setTabCurrent(params.tabCurrent)
      params.statusTabCurrent && setStatusTabCurrent(params.statusTabCurrent)
      getOrderList({
        pageSize: pageDataRef.current.pageSize,
        pageNum: pageDataRef.current.pageNum + 1,
        status: [0],
      })
    } else {
      const params = {
        pageSize: pageDataRef.current.pageSize,
        pageNum: 1,
      }
      getOrderList({
        ...params,
        ...getParams(),
      })
    }
  })
  const onUpdate = async item => {
    const { data } = await http.get(`/core/ticket/search/${item.ticketId}`)
    if (data) {
      const findIndex = orderList.findIndex(i => i.ticketId == item.ticketId)
      orderList[findIndex] = data
      setOrderList([...orderList])
    }
  }

  const changeStatus = async paramsStatus => {
    const { data } = await http.post("/core/ticket/update", {
      ticketId: modalItem.ticketId,
      status: paramsStatus,
    })
    if (data) {
      Taro.showToast({
        title: "操作成功",
        icon: "success",
      })
      setShowModal(false)
      if (tabCurrent == 2) {
        onUpdate(modalItem)
      } else if (paramsStatus == 2) {
        setTabCurrent(1)
        setStatusTabCurrent(2)
      } else if (paramsStatus == 3) {
        setTabCurrent(1)
        setStatusTabCurrent(3)
      } else if (paramsStatus == 4) {
        setTabCurrent(2)
      } else {
        onUpdate(modalItem)
      }
    } else {
      Taro.showToast({
        title: "操作失败",
        icon: "success",
      })
      setShowModal(false)
      onUpdate(modalItem)
    }
  }

  const modalData = {
    confirm: {
      title: "确认接单",
      text: "确认接单后，系统将创建支付订单",
      text2: "如有疑问，请提前联系客户",
      confirmText: "确认接单",
      onConfirm: async () => {
        changeStatus(1)
      },
    },
    cancel: {
      title: "取消订单",
      text: "该订单为待支付订单，请与客户确认后再取消",
      text2: "",
      confirmText: "确认取消",
      onConfirm: () => {
        changeStatus(5)
      },
    },
    threading: {
      title: "穿线完成",
      text: "请确认穿线无误，为保障客户质量，请检查后确认完成",
      text2: "",
      confirmText: "穿线完成",
      onConfirm: () => {
        changeStatus(3)
      },
    },
    take: {
      title: "确认取拍",
      text: "请联系客户，确认客户取拍无误后，点击完成",
      text2: "",
      confirmText: "确认取拍",
      onConfirm: () => {
        changeStatus(4)
      },
    },
    pay: {
      title: "确认已支付",
      text: "请确认钱款是否到账，到账后确认支付已完成",
      text2: "",
      confirmText: "确认已支付",
      onConfirm: () => {
        changeStatus(2)
      },
    },
  }

  return (
    <View className="page-admin-order" onScrollToLower={onScrollLoad} upperThreshold={300} scrollY>
      <View className="tab">
        <View
          className={`tab-item ${tabCurrent == 0 ? "active" : ""}`}
          onClick={() => {
            tabCurrent !== 0 && setTabCurrent(0)
          }}
        >
          待确认
        </View>
        <View
          className={`tab-item ${tabCurrent == 1 ? "active" : ""}`}
          onClick={() => {
            tabCurrent !== 1 && setTabCurrent(1)
          }}
        >
          已确认
        </View>
        <View
          className={`tab-item ${tabCurrent == 2 ? "active" : ""}`}
          onClick={() => {
            tabCurrent !== 2 && setTabCurrent(2)
          }}
        >
          全部
        </View>
      </View>
      {tabCurrent == 1 && (
        <View className="history-tab">
          {statusTab.map(item => {
            return (
              <View
                key={item.value}
                className={`history-tab-item ${statusTabCurrent == item.value ? "active" : ""}`}
                onClick={() => {
                  statusTabCurrent !== item.value && setStatusTabCurrent(item.value)
                }}
              >
                {item.label}
              </View>
            )
          })}
        </View>
      )}
      <ScrollView
        className="order-scroll"
        refresherTriggered={refresherTriggeredStatus}
        onRefresherRefresh={() => {
          setRefresherTriggeredStatus(true)
          const params = {
            pageSize: pageDataRef.current.pageSize,
            pageNum: 1,
          }
          getOrderList({
            ...params,
            ...getParams(),
          })
        }}
        refresherEnabled
        refresherBackground="none"
        onScrollToLower={onScrollLoad}
        upperThreshold={50}
        scrollY
        style={{ top: tabCurrent == 1 ? "200rpx" : "100rpx" }}
      >
        <View className={`order-list ${tabCurrent == 1 ? "has-tab-list" : ""}`}>
          {orderList.map(item => {
            return (
              <AdminOrderItem
                key={item.ticketId}
                itemData={item}
                onClickStatusButton={modalStatus => {
                  setShowModal(modalStatus)
                  setModalItem(item)
                }}
              ></AdminOrderItem>
            )
          })}
        </View>
        {status != "more" && (
          <View style={{ position: "relative", height: "100rpx" }}>
            <AtLoadMore status={status}></AtLoadMore>
          </View>
        )}
      </ScrollView>
      {showModal && (
        <Modal
          isOpened
          titleText={modalData[showModal].title}
          cancelText="取消"
          onCancel={() => setShowModal(false)}
          onConfirm={modalData[showModal].onConfirm}
          confirmText={modalData[showModal].confirmText}
        >
          <View className="modal-text">
            <View>{modalData[showModal].text}</View>
            <View>{modalData[showModal].text2}</View>
          </View>
        </Modal>
      )}
    </View>
  )
}
